<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="flex flex1" style="height: calc(100% - 82px)">
      <div class="left">
        <div>
          <div>帮助列表</div>
          <el-button
            type="primary"
            v-if="has_role_list[3].has_role"
            @click="clear_form_data(), (show_box = true)"
            >新增帮助</el-button
          >
        </div>
        <div
          style="
            height: calc(100% - 63px);
            overflow-y: scroll;
            overflow-x: hidden;
          "
          v-loading="loading"
        >
          <el-menu
            class="el-menu-vertical-demo"
            size="small"
            ref="menu"
            unique-opened
            :default-active="default_menu_id"
            @select="select_menu"
          >
            <div
              v-for="(item, index) in menu_list"
              :key="item.id"
              :index="item.id"
            >
              <el-sub-menu :index="item.id" v-if="item.isShow">
                <template #title>
                  <span style="color: #333">{{ item.dictValue }}</span>
                </template>
                <el-sub-menu
                  v-for="item1 in item.children"
                  :index="item1.id + index"
                  :key="item1.id"
                >
                  <template #title>
                    <span style="color: #333">{{ item1.dictValue }}</span>
                  </template>
                  <el-menu-item
                    v-for="item2 in item1.children"
                    :index="item2.id"
                    :key="item2.id"
                    style="
                      width: 300px;
                      display: inline-block;
                      box-sizing: border-box;
                    "
                    class="text_over"
                    >{{ item2.name }}</el-menu-item
                  >
                </el-sub-menu>
              </el-sub-menu>
            </div>
          </el-menu>
        </div>
      </div>
      <div class="right">
        <div v-if="case_info == ''" class="flex_cc flex_cm">
          <img src="@/assets/img/no_more.png" alt="" />
          <p class="tc c_999">暂无数据</p>
        </div>
        <div v-else>
          <div>
            <div>帮助信息</div>
            <el-button
              type="primary"
              @click="edit"
              v-if="has_role_list[1].has_role"
              >编辑</el-button
            >
          </div>
          <div
            style="height: calc(100% - 65px); overflow-y: auto; padding: 0 20px"
          >
            <div class="desc_box">
              <div class="flex">
                <span style="flex-shrink: 0">帮助名称：</span>
                <el-tooltip :content="case_info?.name" placement="bottom">
                  <span class="text_over">{{ case_info?.name }}</span>
                </el-tooltip>
              </div>
              <div>
                <span>产品分类：</span>
                <span v-for="item in dict_list_1">
                  <span
                    v-if="item.dictCode == case_info?.productCategory"
                    style="color: #333"
                    >{{ item.dictValue }}</span
                  >
                </span>
              </div>
              <div>
                <span>帮助类型：</span>
                <span v-for="item in dict_list_2">
                  <span
                    v-if="item.dictCode == case_info?.courseCategory"
                    style="color: #333"
                    >{{ item.dictValue }}</span
                  >
                </span>
              </div>
              <div><span>排序：</span>{{ case_info?.sort }}</div>
              <div>
                <span>状态：</span
                ><span v-if="case_info?.isEnable">已启用</span>
                <span v-else>已停用</span>
              </div>
            </div>
            <div class="flex_start" style="line-height: 40px">
              <span style="flex-shrink: 0">帮助链接：</span>
              <a
                @click="open(case_info?.url)"
                class="flex1"
                style="
                  display: inline-block;
                  word-break: break-word;
                  margin: 8px 0 8px 0;
                  line-height: 26px;
                  cursor: pointer;
                  color: #3580eb;
                  text-decoration: underline;
                "
              >
                {{ case_info?.url }}
              </a>
            </div>
            <div class="flex_start" style="line-height: 40px">
              <span style="flex-shrink: 0">帮助简介：</span>
              <div
                class="flex1"
                style="
                  white-space: pre-wrap;
                  word-break: break-word
                  overflow-x: scroll;
                  line-height: 26px;
                  margin: 8px 0 8px 0;
                "
              >
                {{ case_info?.introduction }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    @close="resetForm(addcaseform)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增帮助文档</h4>
      <h4 v-else>编辑帮助文档</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        :rules="rules"
        ref="addcaseform"
        label-width="100px"
      >
        <el-form-item label="帮助名称" prop="name">
          <el-input
            v-model="add_form_data.name"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="productCategory">
          <el-select v-model="add_form_data.productCategory">
            <el-option
              v-for="item in dict_list_1"
              :key="item.id"
              :label="item.dictValue"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="帮助类型" prop="courseCategory">
          <el-select v-model="add_form_data.courseCategory">
            <el-option
              v-for="item in dict_list_2"
              :key="item.id"
              :label="item.dictValue"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="帮助链接" prop="url">
          <el-input
            v-model="add_form_data.url"
            placeholder="请输入"
            show-word-limit
            maxlength="300"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input
            v-model="add_form_data.sort"
            placeholder="请输入,若排序为空，则默认排序到最后一位"
            show-word-limit
            maxlength="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="add_form_data.isEnable" :label="true"
            >启用</el-radio
          >
          <el-radio v-model="add_form_data.isEnable" :label="false"
            >停用</el-radio
          >
        </el-form-item>
        <el-form-item label="帮助简介" prop="introduction">
          <el-input
            type="textarea"
            rows="4"
            resize="none"
            v-model="add_form_data.introduction"
            placeholder="请输入"
            show-word-limit
            maxlength="300"
          ></el-input>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button type="primary" v-if="add_form_data.id != ''" @click="copy"
            >复制</el-button
          >
          <el-button @click="resetForm(addcaseform)">取消</el-button>
          <el-button
            v-if="add_form_data.id == ''"
            type="primary"
            :loading="btn_loading"
            @click="submit(addcaseform)"
            >新增</el-button
          >
          <el-button
            v-else
            type="primary"
            :loading="btn_loading"
            @click="submit(addcaseform)"
            >保存</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { check_role, dictData } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import { onBeforeMount, ref, onUnmounted, nextTick } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { getCookie } from '@/utils/cookie'
import { useStore } from 'vuex'
// 页面权限组
const has_role_list = ref([
  { path: '', has_role: false },
  { path: 'helpfile/put', has_role: false },
  { path: 'helpfile/delete', has_role: false },
  { path: 'helpfile/post', has_role: false },
])
nextTick(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
})
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addcaseform = ref<FormInstance>()
const rules = ref({
  name: [{ required: true, message: '请输入帮助名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入帮助链接', trigger: 'blur' }],
  introduction: [
    { required: true, message: '请输入帮助简介', trigger: 'blur' },
  ],
  sort: [{ required: true, message: '请输入帮助排序', trigger: 'blur' }],
  productCategory: [
    { required: true, message: '请选择产品分类', trigger: 'change' },
  ],
  courseCategory: [
    { required: true, message: '请选择帮助类型', trigger: 'change' },
  ],
})
const open = (e) => {
  window.open(e)
}
const header_list = ref([
  {
    label: '帮助名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: true,
    options: [
      { label: '已启用', value: '1' },
      { label: '已停用', value: '0' },
    ],
  },
])
const menu_list = ref() // 左侧列表使用
const default_menu_id = ref()
const menu = ref()
const page_data = ref({
  isEnable: '',
  name: '',
})
const add_form_data = ref({
  id: '',
  name: '',
  sort: '',
  introduction: '',
  //   pic: [],
  isEnable: true,
  courseCategory: '',
  productCategory: '',
  url: '',
})
const member_page_data = ref({
  current: 1,
  pageSize: 10000,
  deptId: '',
  enterpriseId:
    store.state.enterprise_id != '' // 当前登录企业 vuex > cookie
      ? store.state.enterprise_id
      : getCookie('enterprise_id'),
})
const show_box = ref(false)
const dict_list_1 = ref([]) // 产品分类
const dict_list_2 = ref([]) // 帮助分类
onBeforeMount(() => {
  EventBus.on('refresh', () => {
    get_dict_1()
    ElMessage.success('刷新成功！')
  })
  get_dict_1()
})
onUnmounted(() => {
  EventBus.off('refresh')
})

const get_dict_1 = () => {
  dictData('1541665967619182594').then((res) => {
    dict_list_1.value = res as any
    dict_list_1.value.forEach((item) => {
      item.isShow = false
      item.children = []
      item.children_list = []
    })
  })
  dictData('1541665253064970242').then((res) => {
    dict_list_2.value = res as any
    dict_list_2.value.forEach((item) => {
      item.isShow = false
      item.children = []
    })
    get_list()
  })
}
const copy = () => {
  add_form_data.value.id = ''
  add_form_data.value.url = ''
  ElMessage.success('复制成功！')
}
const current_name = ref('')
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  let data = JSON.parse(JSON.stringify(add_form_data.value))
  data.sort = data.sort == '' ? max_length.value + 1 : data.sort
  current_name.value = data.name
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) {
        return
      }
      btn_loading.value = true
      axios
        .request({
          url:
            data.id == ''
              ? serviceApi.help_crud
              : serviceApi.help_crud + '/' + data.id,
          method: data.id == '' ? 'post' : 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            show_box.value = false
            btn_loading.value = false
            get_list()
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const max_length = ref<number>()
const loading = ref(false)
const get_list = () => {
  if (loading.value) return
  loading.value = true
  axios
    .request({
      url: serviceApi.help_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      var a = JSON.parse(JSON.stringify(dict_list_1.value))

      default_menu_id.value = res.data.length
        ? current_name.value == ''
          ? res.data[0].id
          : res.data.filter((i) => {
              return i.name == current_name.value
            })[0].id
        : ''
      let data = res.data.length ? res.data.reverse() : []
      max_length.value = data.length
      if (data.length) {
        a.forEach((item) => {
          data.forEach((item1) => {
            if (item1.productCategory == item.dictCode) {
              item.children_list.push(item1)
            }
          })
          let flag = data.some((item1) => {
            return item1.productCategory == item.dictCode
          })
          if (flag) item.isShow = true
        })
        a.forEach((item) => {
          var b = JSON.parse(JSON.stringify(dict_list_2.value))
          b.forEach((item1) => {
            item.children_list.forEach((i) => {
              if (i.courseCategory == item1.dictCode) {
                item1.children.unshift(i)
              }
            })
          })
          item.children_list.forEach((item1) => {
            let flag = item.children.some((item2) => {
              return item2.dictCode == item1.courseCategory
            })
            if (!flag) {
              b.forEach((i) => {
                if (i.dictCode == item1.courseCategory) {
                  item.children.push(i)
                }
              })
            }
          })
        })
      }
      for (let i in a) {
        a[i].children.sort(function (b, c) {
          return b.dictCode - c.dictCode
        })
      }
      console.log(a, data)
      menu_list.value = a
      loading.value = false
      if (data.length) {
        get_case_info()
      } else {
        case_info.value = ''
      }
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const edit = () => {
  if (add_form_data.value.id == '') {
    get_case_info()
  }
  show_box.value = true
}
const case_info = ref()
const get_case_info = () => {
  axios
    .request({
      url: serviceApi.help_crud + '/' + default_menu_id.value,
      method: 'get',
    })
    .then((res) => {
      console.log(res)
      member_page_data.value.deptId = res.data.id
      add_form_data.value = {
        id: res.data.id,
        name: res.data.name,
        sort: res.data.sort,
        introduction: res.data.introduction,
        // pic: [res.data.pic],
        isEnable: res.data.isEnable,
        url: res.data.url,
        courseCategory: res.data.courseCategory + '',
        productCategory: res.data.productCategory + '',
      }
      case_info.value = JSON.parse(JSON.stringify(add_form_data.value))
    })
}
const select_menu = (index) => {
  console.log(index)
  default_menu_id.value = index
  get_case_info()
}

const search_key = () => {
  page_data.value = {
    isEnable: header_list.value[1].value,
    name: header_list.value[0].value as any,
  }
  console.log(header_list.value, page_data.value)
  dict_list_1.value = []
  dict_list_2.value = []
  get_dict_1()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  clear_form_data()
  show_box.value = false
}
const clear_form_data = () => {
  add_form_data.value = {
    id: '',
    name: '',
    sort: '',
    introduction: '',
    // pic: [],
    isEnable: true,
    courseCategory: add_form_data.value.courseCategory,
    productCategory: add_form_data.value.productCategory,
    url: '',
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-menu) {
  .el-sub-menu__title {
    background-color: #fff;
    &:hover {
      background-color: #fff;
    }
  }
  --el-menu-text-color: #333;
  --el-menu-hover-text-color: #333;
  --el-menu-bg-color: #fff;
  --el-menu-hover-bg-color: #fff;
}
.left {
  width: 300px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #fff;
  > div:first-child {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    border-bottom: 1px solid #d8d8d8;
  }
}
.right {
  flex: 1;
  width: calc(100% - 320px);
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  > div:first-child {
    background-color: #fff;
    > div:first-child {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 20px;
      border-bottom: 1px solid #d8d8d8;
    }

    .desc_box {
      padding: 10px 0 0 0;
      line-height: 40px;
      display: flex;
      flex-wrap: wrap;
      div {
        width: 20%;
      }
    }
    span:first-child {
      color: #999;
    }
  }
  > div:last-child {
    flex: 1;
    height: 100%;
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }
}
</style>
